package com.itsu.application.framework.session;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.concurrent.ConcurrentHashMap;

import cn.hutool.core.util.IdUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public final class Session {

	private static final Log log = LogFactory.get();

	private String id;

	private ConcurrentHashMap<String, Object> attributes;

	private LocalDateTime initTime;

	private LocalDateTime destoryTime;

	public void init() {
		this.id = IdUtil.fastSimpleUUID();
		this.initTime = LocalDateTime.now();
		this.attributes = new ConcurrentHashMap<>();
		log.info("Session init at {}, with sessionid {}", this.initTime.toString(), this.id);
	}

	public void destory() {
		this.destoryTime = LocalDateTime.now();
		log.info("Session destory at {}, with sessionid {}. Session live for {}s", this.destoryTime.toString(), this.id,
				destoryTime.toEpochSecond(ZoneOffset.of("+8")) - initTime.toEpochSecond(ZoneOffset.of("+8")));
	}

	public void setAttribute(String key, Object value) {
		this.attributes.put(key, value);
	}

	public Object getAttribute(String key) {
		return this.attributes.get(key);
	}

	public void removeAttribute(String key) {
		this.attributes.remove(key);
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public ConcurrentHashMap<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(ConcurrentHashMap<String, Object> attributes) {
		this.attributes = attributes;
	}

	public LocalDateTime getInitTime() {
		return initTime;
	}

	public void setInitTime(LocalDateTime initTime) {
		this.initTime = initTime;
	}

	public LocalDateTime getDestoryTime() {
		return destoryTime;
	}

	public void setDestoryTime(LocalDateTime destoryTime) {
		this.destoryTime = destoryTime;
	}

}
